package async

import (
	"fmt"
	"github.com/rafaeldias/async"
	"log"
	"time"
)

// Waterfall 串行执行
func Waterfall() {
	res, err := async.Waterfall(async.Tasks{
		func1,
		func2,
		func3,
	}, "sfs") // 后面的是参数

	log.Println("------------------")

	if err != nil {
		log.Printf("Error: %v\n", err)
		return
	}

	log.Printf("Results: %v\n", res)
}

func func1(prev interface{}) (interface{}, error) {
	return "result1", nil
}

func func2(prev interface{}) (interface{}, error) {
	return prev.(string) + " -> result2", nil
}

func func3(prev interface{}) (interface{}, error) {
	time.Sleep(4000 * time.Microsecond)
	return prev.(string) + " -> result3", nil
}

// Parallel 并行执行返回结果
func Parallel() {

	multiRes, e := async.Parallel(async.MapTasks{
		"one": func() error {
			for i := 'a'; i < 'a'+26; i++ {
				fmt.Printf("%c ", i)
			}
			fmt.Printf("\n")
			return nil //fmt.Errorf("Error in one function")
		},
		"two": func() (int, string, error) {
			time.Sleep(2 * time.Microsecond)
			for i := 0; i < 27; i++ {
				fmt.Printf("%d ", i)
			}
			fmt.Printf("\n")
			return 2, "test", nil
		},
		"three": func() int {
			for i := 'z'; i >= 'a'; i-- {
				fmt.Printf("%c ", i)
			}
			fmt.Printf("\n")
			return 3
		},
	})

	if e != nil {
		log.Printf("Error executing a Parallel (%s)", e)
	}

	log.Printf("Parallel Result key %s: %+v\n", "two", multiRes.Key("two"))

}
